// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()

const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate
const db_orders = db.collection('orders');

//操作excel用的类库
const xlsx = require('node-xlsx');

// 云函数入口函数
exports.main = async (event, context) => {
  console.log(event)
  switch (event.action) {
    case 'getOrderAll':
      return getOrderAll(event)
    case 'getOrder':
      return getOrder(event)
    case 'exportOrder':
      return exportOrder(event)
    default:
      return
  }
}

//导出order数据
async function exportOrder(event) {
  try {
    let orderList = await getOrderAll(event);
    console.log(orderList)
    console.log(orderList.list)
    const name = '订餐.xlsx';
    let alldata = []
    let row = ['序号', '餐厅', '餐别', '餐数', '订餐人', '部门', '日期']
    alldata.push(row)

    // let data = orderList.data
    let data = orderList.list
    for (const key in data) {
      let arr = []
      console.log(key)
      arr.push(parseInt(key) + 1)
      arr.push(data[key].room)
      arr.push(parseOrderType(data[key].order_type))
      arr.push(data[key].order_count)
      arr.push(data[key].person)
      arr.push(data[key].department)
      arr.push(data[key].extra_order_date)
      alldata.push(arr)
    }

    //3，把数据保存到excel里
    let buffer = await xlsx.build([{
      name: '订餐',
      data: alldata
    }])

    //4，把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: name,
      fileContent: buffer
    })

  } catch (error) {
    console.error(error)
    return error
  }

}

function getOrder(e) {
  return db_orders.where({
    extra_order_date: _.gte(formatDate(new Date()).date_week)
  }).get({
    success: res => {
      console.log(res)
    }
  })
}

function parseOrderType(type) {
  switch (type) {
    case '1':
      return '早餐'
    case '2':
      return '午餐'
    case '3':
      return '晚餐'
    default:
      return '未知'
  }
}

//获取order所有列表
function getOrderAll(event) {
  try {
    return db_orders.aggregate()
      .match({
        extra_order_date: _.gte(formatDate(new Date()).date_week)
      })
      .lookup({
        from: "user",
        localField: "person",
        foreignField: "name",
        as: "userList"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$userList', 0]), '$$ROOT'])
      })
      .project({
        userList: 0,
        password: 0
      }).end()
    // .then(res => {
    //   console.log(res)
    //   arr = res

    // })
    // .catch(err => {
    //   console.error(err)
    // })
    // return arr
  } catch (error) {
    console.error(error)
  }
}

const formatDate = date => {
  let show_day = new Array('周日', '周一', '周二', '周三', '周四', '周五', '周六');
  let year = date.getFullYear();
  let month = ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : date.getMonth() + 1);
  let day = (date.getDate() < 10 ? ("0" + date.getDate()) : date.getDate());
  let week = show_day[new Date(date).getDay()];
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()


  // return `${year}-${month}-${day}.${week}`;
  return {
    "date": `${year}-${month}-${day}`,
    "time": [hour, minute, second].map(formatNumber).join(':'),
    "week": `${week}`,
    "date_week": `${year}-${month}-${day}.${week}`
  };
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}